package cc.creativecomputing.resonate.journal;

import cc.creativecomputing.graphics.texture.CCTextureData;
import cc.creativecomputing.math.CCMath;
import cc.creativecomputing.math.CCVector3f;

public class MJTargetFinder {
	
	public boolean isRunning = false;
	private CCTextureData _myTextureData;
	private CCVector3f[][] _myTargets;
	private int _myIndexWidth;
	private int _myIndexHeight;
	private int targetAreaWidth;
	private int targetAreaHeight;
	
	
	class Process implements Runnable {
		public void run() {
			
			int i = 0;
			int j = 0;
			while(on()) {
				int x = (int)CCMath.random(0, _myTextureData.width());
				int y = (int)CCMath.random(0, _myTextureData.height());
				
				float tx = x / (float)_myTextureData.width();
				float ty = y / (float)_myTextureData.height();
				
				_myTargets[i][j] = new CCVector3f(0,0,0);
				if (_myTextureData.getPixel(x,y).r>0) {
					_myTargets[i][j] = new CCVector3f(tx,ty,0);
					i+=1; 
					if (i>=_myIndexWidth) {
						i = 0;
						j+=1;
					}
					if (j>=_myIndexHeight) {
						System.out.println("DONE");
						isRunning = false;
						return;
					}
				}
			}
		}
	}
	
	public synchronized boolean on() {
		return isRunning;
	}
	public synchronized void stop() {
		isRunning = false;
	}
	
	private Thread _myThread;
	
	public MJTargetFinder () {
		_myThread = new Thread(new Process());
	}
	
	public void addNewTexture (CCTextureData theTexture, float indexWidth, int particleW, int particleH, int targetAreaH, int targetAreaW) {
		_myTextureData = theTexture;
		_myIndexWidth = (int)(indexWidth*particleW);
		_myIndexHeight = particleH;
		targetAreaWidth = targetAreaW;
		targetAreaHeight = targetAreaH;
		
		_myTargets = new CCVector3f[particleW][particleH];
		for (int i=0; i<particleW; i++) {
			for (int j=0; j<particleH; j++) {
				_myTargets[i][j] = new CCVector3f(0,0,0);
			}
		}
		int i=0;
		int j=0;
		while(true) {
			int x = (int)CCMath.random(0, _myTextureData.width());
			int y = (int)CCMath.random(0, _myTextureData.height());
			
			float tx = x / (float)_myTextureData.width() * targetAreaWidth - targetAreaWidth/2;
			float ty = y / (float)_myTextureData.height()* targetAreaHeight - targetAreaHeight/2;
			
			_myTargets[i][j] = new CCVector3f(0,0,0);
			if (_myTextureData.getPixel(x,y).r>0) {
				_myTargets[i][j] = new CCVector3f(tx,ty,0);
				i+=1; 
				if (i>=_myIndexWidth) {
					i = 0;
					j+=1;
				}
				if (j>=_myIndexHeight) {
					System.out.println("DONE");
					isRunning = false;
					return;
				}
			}
		}
	}
	public void print() {
		for (int i=0; i<100; i++) {
			for (int j=0; j<100; j++) {
				System.out.print(_myTargets[i][j]+" ");
			}
			System.out.println();
		}
	}
	
	public CCVector3f[][] getTargets() {
		return _myTargets;
	}
}
